package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import entity.User;

@WebServlet("/userList")
public class UserPageDataServlet extends HttpServlet {
	
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		final int SIZE = 6;
		Integer role = null;
		try {
			role = Integer.parseInt(request.getParameter("selectRole"));
		}catch (Exception e){
		}
		System.out.println("------------userList-------------");
		String account = request.getParameter("selectAccount");
		String userName = request.getParameter("selectName");
		StringBuilder condition = new StringBuilder();
		StringBuilder urlParams =new StringBuilder();
		ArrayList<Object> parmas = new ArrayList<>();
		condition.append("1=1");
		if (role != null){
			System.out.println(role);
			condition.append(" and role=?");
			parmas.add(role);
			urlParams.append("&selectRole=" + role);
		}
		if(account != null && !account.isEmpty()){
			System.out.println(account);
			condition.append(" and account like ?");
			parmas.add("%" + account + "%");
			urlParams.append("&selectAccount=" + URLEncoder.encode(account,"utf-8"));
		}
		if (userName != null && !userName.isEmpty()){
			System.out.println(userName);
			condition.append(" and user_name like ?");
			parmas.add("%" + userName + "%");
			urlParams.append("&selectName=" + URLEncoder.encode(userName,"utf-8"));
		}
		Integer page = null;
		try {
			page = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {
			page = 1;
		}
		int start = (page - 1)*SIZE;
		UserDao dao = new UserDao();
		List<User> list = dao.queryUserPage(start, SIZE, condition.toString(), parmas);
		int total = dao.total_user(condition.toString(),parmas);
		int pageNum = total / SIZE;
		if (total % SIZE != 0) {
			pageNum += 1;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i <= pageNum; i++) {
			String str = "<a href=\"#url\">第" + i + "页</a>&nbsp;&nbsp;";
			str = str.replace("#url", request.getContextPath() + "/userList?page=" + i + urlParams.toString());
			System.out.println("/userList?page=" + i + urlParams.toString());
			if (page == i) {
				str = "第" + i + "页&nbsp;&nbsp;";
			}
			sb.append(str);
		}
		System.out.println(sb);
		request.setAttribute("page", sb.toString());
		request.setAttribute("users", list);
		request.getRequestDispatcher("./user_list.jsp").forward(request, response);
	}


}
